package cn.com.czpb.client.module.personal.acticity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.custorm.RecycleViewDivider;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.usercenter.CollectBean;
import cn.com.czpb.client.model.usercenter.CollectEntity;
import cn.com.czpb.client.model.usercenter.EmptyEntity;
import cn.com.czpb.client.module.news.activity.NewsAlbum_Activity;
import cn.com.czpb.client.module.news.activity.NewsDetailActivity;
import cn.com.czpb.client.module.news.activity.NewsVideoActivity;
import cn.com.czpb.client.module.news.activity.ZhuantiActivityNew;
import cn.com.czpb.client.module.personal.adapter.CollectionAdapter;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.AAnim;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class CollectionActivity extends MToolBarActivity implements BaseQuickAdapter.OnItemChildClickListener,
        OnLoadmoreListener,OnRefreshListener, BaseQuickAdapter.OnItemChildLongClickListener {
    @BindView(R.id.swipe_layout)
    SmartRefreshLayout swipe_layout;
    @BindView(R.id.tv_empty_collection_activity)
    TextView tv_empty_collotion_activity;
//    @BindView(R.id.title_toolbar)
//    TextView tv_title;
    @BindView(R.id.ptrlistview_activity_collection)
    RecyclerView ptrlistview;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.layout_title)
    TextView layout_title;

    private CollectionAdapter adapter;
    private List<CollectBean> list;
    private int Page = 1;
    private static final int PageSize = 15;
    private boolean mFlagRefresh = true;//刷新还是加载


    @Override
    protected int setLayoutId() {
        return R.layout.activity_collection;
    }
    @Override
    public void initData() {
        super.initData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        tv_title.setText("我的收藏");
        init();
    }

    private void init() {
        layout_title.setText("我的收藏");
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        list = new ArrayList<>();
        getCollectionInfoFromServer();
        adapter = new CollectionAdapter(list,spu.getShowImage());
        GridLayoutManager manager = new GridLayoutManager(activity, 1);
        ptrlistview.setLayoutManager(manager);
        ptrlistview.setAdapter(adapter);
        int height = (int) getResources().getDimension(R.dimen.x2);
        ptrlistview.addItemDecoration(new RecycleViewDivider(activity,
                LinearLayoutManager.HORIZONTAL, height,
                getResources().getColor(R.color.color_e8e8e8)));
        adapter.setOnItemChildClickListener(this);
//
//        swipe_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                mFlagRefresh=true;
//                Page=1;
//                showDialog();
//                list.clear();
//                getCollectionInfoFromServer();
//            }
//        });


        swipe_layout.setOnRefreshListener(this);
        swipe_layout.setRefreshHeader(new ClassHeader_other(this));
        swipe_layout.setOnLoadmoreListener(this);

    }


    private void mycollectionItemLongclick(BaseQuickAdapter adapter, View view, int position) {
        CollectBean cb = (CollectBean) adapter.getItem(position);
        Map map = new HashMap();
        map.put("uid", spu.getUser().getUid());
        map.put("fid", cb.getId());
        LogUtils.e(spu.getUser().getUid() + "-----" + cb.getId());
        Factory.provideHttpService().deletecollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity emptyEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity emptyEntity) {

                        TUtils.toast(emptyEntity.msg);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }


    private void getCollectionInfoFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("uid", spu.getUser().getUid());
        Factory.provideHttpService().collection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CollectEntity, Boolean>() {
                    @Override
                    public Boolean call(CollectEntity collectEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CollectEntity>() {
                    @Override
                    public void call(CollectEntity collectEntity) {
                        LogUtils.e("code--" + collectEntity.code);
                        if (mFlagRefresh) {
                            swipe_layout.finishRefresh();

                        }
                        if ("200".equals(collectEntity.code)) {
                            LogUtils.e("code--" + collectEntity.msg);

                            setListData(collectEntity.data.getList());
                            adapter.notifyDataSetChanged();
                            LogUtils.e(list.size() + "");
                        } else if ("209".equals(collectEntity.code)) {

                            list.clear();
                            adapter.notifyDataSetChanged();
                        } else {
                            if (!mFlagRefresh) {
                                Page--;
                            }
                        }
                        mFlagRefresh = false;
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable--" + throwable.getMessage());
                    }
                });


    }

    public void setListData(List<CollectBean> list) {
        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < PageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }


    private void mycollectionItemclick(BaseQuickAdapter adapter, View view, int position) {
        CollectBean cb = (CollectBean) adapter.getItem(position);
        Intent intent = new Intent();
        intent.putExtra("from", "collection");
        NewsBean nb = new NewsBean();
        nb.setTid(cb.getData().getTid());
//        nb.setNid(cb.getData().getContentid());
        nb.setNid(cb.getData().getNid());
        nb.setImgs(cb.getData().getImgs());
        boolean flag = false;//是否是预定类型
        //跳转脚标）1新闻  2图集  3视频 4html5
        LogUtils.e("type-->" + cb.getType());
        if ("1".equals(cb.getData().getRtype())) {
            intent.putExtra("newbean", nb);
            flag = true;
            intent.setClass(CollectionActivity.this, NewsDetailActivity.class);
        } else if ("2".equals(cb.getData().getRtype())) {
            intent.putExtra("newbean", nb);
            intent.putExtra("nid", cb.getData().getContentid());
            intent.putExtra("rvalue", cb.getData().getRvalue());
            flag = true;
            intent.setClass(CollectionActivity.this, NewsAlbum_Activity.class);
        } else if ("4".equals(cb.getData().getRtype())) {
            intent.putExtra("newbean", nb);
            intent.putExtra("nid", cb.getData().getContentid());
            intent.putExtra("rvalue", cb.getData().getRvalue());
            flag = true;
            intent.setClass(CollectionActivity.this, ZhuantiActivityNew.class);
        } else if ("6".equals(cb.getData().getRtype())) {
            intent.putExtra("newbean", nb);
            intent.putExtra("nid", cb.getData().getContentid());
            intent.putExtra("rvalue", cb.getData().getRvalue());
            flag = true;
            intent.setClass(CollectionActivity.this, NewsVideoActivity.class);
        }else {
            intent.putExtra("newbean", nb);
            flag = true;
            intent.setClass(CollectionActivity.this, NewsDetailActivity.class);
        }
        if (flag) {
            startActivity(intent);
            AAnim.startScreen(activity);
        }
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        mycollectionItemclick(adapter, view, position);
    }

//    @Override
//    public void onLoadMoreRequested() {
//        Page++;
//        showDialog();
//        getCollectionInfoFromServer();
//    }

    @Override
    public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                mFlagRefresh = true;
                Page = 1;
                list.clear();
                getCollectionInfoFromServer();
            }
        },2000);
        swipe_layout.setLoadmoreFinished(false);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        Page++;

        getCollectionInfoFromServer();
        swipe_layout.finishLoadmore();
        swipe_layout.setLoadmoreFinished(true);
    }
}
